package upmc.fr.android.rss.parser;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

import upmc.fr.android.model.RSSArticle;
import upmc.fr.android.model.RSSFlow;

public class RSSFlowReader implements IRSSFlowReader
{
	private RSSHandler handler = RSSHandler.getInstance();

	@Override
	public void update(RSSFlow flow) throws RSSReadingException
	{		
		RSSFlow res = read(flow.getUrl());			
		for(int i=0; i<res.getAllArticles().size(); i++)
		{
			RSSArticle remoteArticle = res.getArticle(i);			
			if(flow.getAllArticles().contains(remoteArticle))
			{
				RSSArticle localArticle = flow.getArticle(flow.getAllArticles().indexOf(remoteArticle));
				remoteArticle.setRead(localArticle.isRead());
				remoteArticle.setHidden(localArticle.isHidden());
			}
			else
				flow.addArticle(remoteArticle);
		}	
	}

	@Override
	public RSSFlow read(String url) throws RSSReadingException
	{
		try 
		{
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();		
			
			parser.parse(url, handler);
			return handler.getResult();
		}
		catch (ParserConfigurationException e) 
		{		
			throw new RSSReadingException("Configuration du parseur incorrecte");
		}
		catch (SAXException e) 
		{		
			throw new RSSReadingException("Probleme de parsing");
		}
		catch (IOException e) 
		{		
			throw new RSSReadingException(e.getMessage());
		}		
	}

	public static void main(String[] args) 
	{
		RSSFlowReader reader = new RSSFlowReader();
		try 
		{
			RSSFlow flow = reader.read("http://www.lemonde.fr/rss/une.xml");
			System.out.println(flow.getTitle());
			System.out.println(flow.getDescription());
		}
		catch (RSSReadingException e) 
		{		
			e.printStackTrace();
		}
	}
}
